//
//  PickerCollectionViewController.m
//  photoLibrayIos8
//
//  Created by jing zhao on 4/20/16.
//  Copyright © 2016 jing zhao. All rights reserved.
//

#import "PickerCollectionViewController.h"
#import "UICollectionViewLeftAlignedLayout.h"
#import "NSString+LocalString.h"
#import "UIColor+LocalColor.h"
#import "PickerCollectionViewCell.h"
#import "PickerContentViewController.h"
#import "SelectTableView.h"
#import "UploadViewController.h"
#import "PickerHeader.h"

@interface PickerCollectionViewController ()   <UICollectionViewDataSource,
UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout,
DelegatePickerCollectionViewCell,
DelegateSelectTableView,
DelegatePickerContent>

@property (strong, nonatomic)PickerCollectionViewCell *collectionContentCell;
@property (nonatomic,strong) NSMutableArray *arrayAlbumsFetch;
@property (nonatomic,strong) NSDictionary *dicLoad;
@property (assign,nonatomic) PHAssetMediaType mediaTypeSlect;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UILabel *labelTitle;
@property (weak, nonatomic) IBOutlet UILabel *labelPickerNum;
@property (weak, nonatomic) IBOutlet UIImageView *imageArrowUpDown;
@property (strong,nonatomic)SelectTableView* tableViewSelect;

@property (assign, nonatomic)NSInteger selectPhotoAssetNum;
@property (strong, nonatomic)NSMutableArray *selectArray;

@end

@implementation PickerCollectionViewController

static NSString * const reuseIdentifier = @"Cell";

-(void)setSelectMediaType:(PHAssetMediaType)inputMediaType{
    self.mediaTypeSlect = inputMediaType;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent=YES;
    [self.navigationController.navigationBar setHidden:YES];
    [self setNextButtonStatus];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.selectPhotoAssetNum = 0;
    self.selectArray = [NSMutableArray array];
    self.labelPickerNum.text = [NSString stringWithFormat:@"0/9 %@",@"selected"];
   
    //init
    UICollectionViewFlowLayout *collectionFlow = (UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout;
    collectionFlow.minimumLineSpacing = 3.0;
    collectionFlow.minimumInteritemSpacing = 3.0;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"PickerCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:IDENTIFYCOLLECTIONPICKERCELL];
    self.arrayAlbumsFetch = [NSMutableArray array];
    
    PHFetchOptions *fetchType = [PHFetchOptions new];
    fetchType.predicate =  [NSPredicate predicateWithFormat:@"mediaType==%d", self.mediaTypeSlect];
    
    //随时更新相册 和 用户创建相册
    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
    PHFetchResult *userCreatAlbum = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAny options:nil];
    
    for (PHCollection *collection in smartAlbums)
        [self dealWithCollectionWith:collection WithPHFetchResult:fetchType];
    for (PHCollection *collection in userCreatAlbum)
        [self dealWithCollectionWith:collection WithPHFetchResult:fetchType];
    
    if ([self.arrayAlbumsFetch count]>0) {
        self.dicLoad =[self.arrayAlbumsFetch objectAtIndex:0];
        PHAssetCollection *collection = [self.dicLoad objectForKey:KEYPHASSETCOLLECTION];
        self.labelTitle.text= [NSString transformAblumTitle:collection.localizedTitle];
        float heightTable =55.0*3;
        if ([self.arrayAlbumsFetch count]*55<55*3) {
            heightTable=[self.arrayAlbumsFetch count]*55.0;
        }
        float statusBarHeight = [[UIApplication sharedApplication]statusBarFrame].size.height+44;
        //selectTabel
        self.tableViewSelect = [[[NSBundle mainBundle]loadNibNamed:@"SelectTableView" owner:self options:nil] firstObject];
        self.tableViewSelect.translatesAutoresizingMaskIntoConstraints = NO;
        [self.tableViewSelect setBackgroundColor:[UIColor colorWithRed:242/255.0f green:102/255.0f blue:71/255.0f alpha:1.0]];
        [self.tableViewSelect configureData:self.arrayAlbumsFetch andDelegateSelect:self];
        [self.view addSubview:self.tableViewSelect];
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_tableViewSelect]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_tableViewSelect)]];
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-statusBarHeight-[_tableViewSelect(==heightTable)]" options:0 metrics:@{@"heightTable":[NSNumber numberWithFloat:heightTable],@"statusBarHeight":[NSNumber numberWithFloat:statusBarHeight]} views:NSDictionaryOfVariableBindings(_tableViewSelect)]];
        self.tableViewSelect.hidden = YES;
        [self.collectionView reloadData];
    }else{
        self.labelTitle.text =  @"没有该类型资源相册";
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark public -- 提取相册中照片和视频

-(void)dealWithCollectionWith:(PHCollection *)collection WithPHFetchResult:(PHFetchOptions*)fetchResult{
    PHAssetCollection *assetCollection = (PHAssetCollection *)collection;
    PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:fetchResult];
    if ([assetsFetchResult count]>0) {
        NSMutableArray *array = [NSMutableArray  array];
        for (PHAsset *asset in assetsFetchResult) {
            NSDictionary *dic =@{KEYAsset:asset,KEYSelect:[NSNumber numberWithBool:NO]};
            [array addObject:dic];
        }
        NSDictionary *dic = @{KEYPHASSETCOLLECTION:assetCollection,KEYPHFETCHRESULT:array};
        [self.arrayAlbumsFetch addObject:dic];
    }
}


#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSArray *array = [self.dicLoad objectForKey:KEYPHFETCHRESULT];
    return [array count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PickerCollectionViewCell *pickCell = [collectionView dequeueReusableCellWithReuseIdentifier:IDENTIFYCOLLECTIONPICKERCELL forIndexPath:indexPath];
    NSDictionary *dataDic =[[self.dicLoad objectForKey:KEYPHFETCHRESULT]objectAtIndex:indexPath.row];
    [pickCell configureDataDictionary:dataDic andDelegate:self andIndexPath:indexPath];
    // Configure the cell
    return pickCell;
}

#pragma mark <UICollectionViewDelegate>

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    float screenWidth =[UIScreen mainScreen].bounds.size.width;
    float  width = (screenWidth-3*4-1)/3.0;
    return CGSizeMake(width,width);    
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(3, 3, 3, 3);
}

#pragma mark <DelegatePickerCollectionViewCell>

-(void)changeDicSelectWithDic:(NSDictionary *)dic{
    BOOL boolSelect = [[dic objectForKey:KEYSelect]boolValue];
    if (!boolSelect) {
        if ([self.selectArray count]+1>9) {
            UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"提醒" message:@"你已选择超过9个" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil];
            [alert show];
        }else{
            
            NSArray *arrayFetch = [self.dicLoad objectForKey:KEYPHFETCHRESULT];
            NSInteger index = [arrayFetch indexOfObject:dic];
            NSDictionary *dicReset = @{KEYSelect:[NSNumber numberWithBool:!boolSelect],KEYAsset:dic[KEYAsset]};
            NSMutableArray *mutArrayFetch = [NSMutableArray arrayWithArray:arrayFetch];
            [mutArrayFetch replaceObjectAtIndex:index withObject:dicReset];
            self.dicLoad = @{KEYPHASSETCOLLECTION:[self.dicLoad objectForKey:KEYPHASSETCOLLECTION],KEYPHFETCHRESULT:mutArrayFetch};
            
            [self.selectArray addObject:dicReset];
            self.labelPickerNum.text = [NSString stringWithFormat:@"%ld/9 %@",(long)[self.selectArray count],@"selected"];
            [self setNextButtonStatus];
        }
    }else{
        //删除
        NSInteger indexTemp = [self.selectArray indexOfObject:dic];
        [self.selectArray removeObjectAtIndex:indexTemp];
        self.labelPickerNum.text = [NSString stringWithFormat:@"%ld/9  %@",(long)[self.selectArray count],@"selected"];
        [self setNextButtonStatus];
        
        //dicLoad
        NSArray *arrayFetch = [self.dicLoad objectForKey:KEYPHFETCHRESULT];
        NSInteger index = [arrayFetch indexOfObject:dic];
        NSDictionary *dicReset = @{KEYSelect:[NSNumber numberWithBool:!boolSelect],KEYAsset:dic[KEYAsset]};
        NSMutableArray *mutArrayFetch = [NSMutableArray arrayWithArray:arrayFetch];
        [mutArrayFetch replaceObjectAtIndex:index withObject:dicReset];
        self.dicLoad = @{KEYPHASSETCOLLECTION:[self.dicLoad objectForKey:KEYPHASSETCOLLECTION],KEYPHFETCHRESULT:mutArrayFetch};
    }
}

#pragma mark collectionCell

-(void)delegateSelectPickerCollectionViewCell:(NSObject*)object{
    PickerCollectionViewCell *pickerCell = (PickerCollectionViewCell*)object;
    NSDictionary *dicTemp = [[self.dicLoad objectForKey:KEYPHFETCHRESULT]objectAtIndex:pickerCell.indexPath.row];
    BOOL boolSelect = [[dicTemp objectForKey:KEYSelect]boolValue];
    if (!boolSelect) {
        if ([self.selectArray count]+1<=9){
            pickerCell.buttonSelect.selected = YES;
            pickerCell.viewOpacity.hidden = NO;
        }
    }else{
        pickerCell.buttonSelect.selected  = NO;
        pickerCell.viewOpacity.hidden = YES;

    }
        [self changeDicSelectWithDic:dicTemp];
}

-(void)delegateAllSelectPickerCollectionViewCell:(NSObject*)object{
    self.collectionContentCell = (PickerCollectionViewCell*)object;
    [self performSegueWithIdentifier:@"performContent" sender:object];
}

#pragma mark DelegateSelectTableView

-(void)delegateSelect:(NSDictionary*)dic{
    PHAssetCollection *collection = [dic objectForKey:KEYPHASSETCOLLECTION];
    PHAssetCollection *collectionNow = [self.dicLoad objectForKey:KEYPHASSETCOLLECTION];
    if (![collection.localizedTitle isEqualToString:collectionNow.localizedTitle]) {
        [self.arrayAlbumsFetch replaceObjectAtIndex:self.selectPhotoAssetNum withObject:self.dicLoad];
        self.selectPhotoAssetNum = [self.arrayAlbumsFetch indexOfObject:dic];
        self.dicLoad = dic;
        [self.collectionView reloadData];
    }
    
    self.tableViewSelect.hidden = YES;
    self.labelTitle.text= [NSString transformAblumTitle:collection.localizedTitle];
}

#pragma mark DelegatePickerContent
-(void)delegateSelectPicker:(NSDictionary*)dicData{
    self.collectionContentCell.buttonSelect.selected =  !self.collectionContentCell.buttonSelect.selected;
    self.collectionContentCell.viewOpacity.hidden = !self.collectionContentCell.viewOpacity.hidden;
    [self changeDicSelectWithDic:dicData];
}

#pragma mark button

- (IBAction)back:(id)sender {
    [[NSNotificationCenter defaultCenter]postNotificationName:NOTIFICATIONUPLOADERROR object:nil];
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (IBAction)changeData:(id)sender {
    self.tableViewSelect.hidden = !self.tableViewSelect.hidden;
    if (self.tableViewSelect.hidden)
        [self.imageArrowUpDown setImage:[UIImage imageNamed:@"down_icon_white"]];
    else
        [self.imageArrowUpDown setImage:[UIImage imageNamed:@"up_icon_white"]];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.destinationViewController isKindOfClass:[PickerContentViewController class]]) {
        PickerCollectionViewCell *pickerCell = (PickerCollectionViewCell*)sender;
        NSDictionary *dataDic =[[self.dicLoad objectForKey:KEYPHFETCHRESULT]objectAtIndex:pickerCell.indexPath.row];
        PickerContentViewController *contentViewController = segue.destinationViewController;
        contentViewController.delegatePickContent = self;
        [contentViewController configureData:dataDic andSelectArray:self.selectArray];
    }
    else if ([segue.destinationViewController isKindOfClass:[UploadViewController class]]){
        if([self.selectArray count]> 0){
            UploadViewController *UploadView = (UploadViewController*)segue.destinationViewController;
            [UploadView setDataArray: self.selectArray];
        }else{
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"消息" message:@"你没有选中任何图片" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
            [alertView show];
        }
    }
}
-(void)setNextButtonStatus{
    
    if (_selectArray.count == 0) {
        self.nextBtn.enabled = NO;
    }else{
        self.nextBtn.enabled = YES;
    }
}

@end
